/*
 * @Author: Zhouhai 497675647@qq.com
 * @Date: 2023-02-10 20:57:34
 * @LastEditors: Zhouhai 497675647@qq.com
 * @LastEditTime: 2023-03-03 17:13:03
 */
import Taro from "@tarojs/taro"
import { pageToLogin } from "./utils"
import { HTTP_STATUS_CODE } from './httpStatusCode'
import constant from '@/servers/constant';

const customInterceptor = (chain) => {

  const requestParams = chain.requestParams

  return chain.proceed(requestParams).then(res => {
    // 只要请求成功，不管返回什么状态码，都走这个回调
    if (res.data.code === HTTP_STATUS_CODE.NOT_FOUND) {
      return Promise.reject(new Error("请求资源不存在"))
    } else if (res.data.code === HTTP_STATUS_CODE.BAD_GATEWAY) {
      return Promise.reject(new Error("服务端出现了问题"))
    } else if (res.data.code === HTTP_STATUS_CODE.FORBIDDEN) {
      Taro.setStorageSync(constant.token, "")
      pageToLogin()
      // TODO 根据自身业务修改
      return Promise.reject(new Error("当前操作没有权限"))
    } else if (res.data.code === HTTP_STATUS_CODE.AUTHENTICATE) {
      Taro.setStorageSync(constant.token, "")
      pageToLogin()
      return Promise.reject(new Error("认证失败，无法访问系统资源"))
    } else if (res.data.code === HTTP_STATUS_CODE.SUCCESS) {
      return res.data

    }else{
      Taro.showToast({
        title: res.data.msg,
        icon: 'error',
        duration: 2000
      })
      return Promise.reject(new Error(msg))
    }
  })
}

// Taro 提供了两个内置拦截器
// logInterceptor - 用于打印请求的相关信息
// timeoutInterceptor - 在请求超时时抛出错误。
const interceptors = [customInterceptor, Taro.interceptors.logInterceptor]

export default interceptors
